﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace TuoPu镭雕机注册SN并过站
{
    class PostAPI
    {
        public static string postsend(string url, string content)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";

            #region 添加Post 参数
            // byte[] data = Encoding.UTF8.GetBytes(content);
            byte[] data = Encoding.ASCII.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public static string AppServerPost =
            SystemConfig.GetConfigData("AppServer", string.Empty) + "/imsapi/rest/actions/";

        public static string regLogin(
            string stationNumber,
            string stationPassword,
            string user,
            string password,
            string client,
            string registrationType,
            string systemIdentifier
        )
        {
            string url = AppServerPost + "regLogin";

            var sessionValidationStruct = new JObject
            {
                ["stationNumber"] = stationNumber,
                ["stationPassword"] = stationPassword,
                ["user"] = user,
                ["password"] = password,
                ["client"] = client,
                ["registrationType"] = registrationType,
                ["systemIdentifier"] = systemIdentifier
            };

            var payload = new JObject
            {
                ["sessionValidationStruct"] = sessionValidationStruct
            };

            string Params = JsonConvert.SerializeObject(payload);
            return postsend(url, Params);
        }

        public static JObject getSessionContext()
        {
            var regLoginResult = regLogin(
                SystemConfig.GetConfigData("Station", string.Empty),
                "-1",
                SystemConfig.GetConfigData("user", string.Empty),
                SystemConfig.GetConfigData("password", string.Empty),
                "01",
                "-1",
                "-1"
            );

            var resultObj = JsonConvert.DeserializeObject<JObject>(regLoginResult);
            var sessionContextToken = resultObj?["result"]?["sessionContext"];
            if (sessionContextToken == null)
                throw new InvalidOperationException("Session context not found in regLogin response.");

            return sessionContextToken.Type == JTokenType.Object
                ? (JObject)sessionContextToken
                : JsonConvert.DeserializeObject<JObject>(sessionContextToken.ToString());
        }

        public static string trAssignSerialNumberForProductOrWorkOrder_TUOPU(
            string stationNumber,
            string workOrderNumber,
            string partNumber,
            string bomVersion,
            string serialNumberRef,
            string serialNumberRefPos,
            string processLayer,
            string activateWorkOrder,
            ArrayList array
        )
        {
            var json = new JObject
            {
                ["sessionContext"] = getSessionContext(),
                ["stationNumber"] = stationNumber,
                ["workOrderNumber"] = workOrderNumber,
                ["partNumber"] = partNumber,
                ["bomVersion"] = bomVersion,
                ["serialNumberRef"] = serialNumberRef,
                ["serialNumberRefPos"] = serialNumberRefPos
            };

            var serialNumberArray = new JArray();
            for (int i = 0; i < array.Count; i++)
            {
                var serialObj = new JObject
                {
                    ["serialNumber"] = array[i]?.ToString() ?? string.Empty,
                    ["serialNumberOld"] = string.Empty,
                    ["serialNumberPos"] = (i + 1).ToString()
                };
                serialNumberArray.Add(serialObj);
            }

            json["serialNumberArray"] = serialNumberArray;
            json["processLayer"] = processLayer;
            json["activateWorkOrder"] = activateWorkOrder;

            string Params = JsonConvert.SerializeObject(json);
            string url = AppServerPost + "trAssignSerialNumberForProductOrWorkOrder";
            return postsend(url, Params);
        }

        public static string trUploadState(
            string stationNumber,
            string processLayer,
            string serialNumberRef
        )
        {
            var json = new JObject
            {
                ["sessionContext"] = getSessionContext(),
                ["stationNumber"] = stationNumber,
                ["processLayer"] = processLayer,
                ["serialNumberRef"] = serialNumberRef,
                ["serialNumberRefPos"] = "1",
                ["serialNumberState"] = "0",
                ["duplicateSerialNumber"] = "1",
                ["bookDate"] = "-1",
                ["cycleTime"] = "0"
            };
            string Params = JsonConvert.SerializeObject(json);
            string url = AppServerPost + "trUploadState";
            return postsend(url, Params);
        }
    }
}
